package com.example.shangjiba;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * 书籍列表Activity
 */
public class BookListActivity extends AppCompatActivity {

    private EditText etBookNo;
    private EditText etBookName;
    private Button btnAdd;
    private Button btnDelete;
    private Button btnUpdate;
    private Button btnQuery;
    private RecyclerView recyclerView;
    private BookAdapter bookAdapter;
    
    private BookDatabaseHelper dbHelper;
    private String currentUserEmail;
    private Book selectedBook;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);
        
        // 设置标题
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("我的书籍");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        initViews();
        initData();
        initRecyclerView();
        loadAllBooks();
    }

    private void initViews() {
        etBookNo = findViewById(R.id.et_book_no);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        recyclerView = findViewById(R.id.recycler_view_books);
    }

    private void initData() {
        dbHelper = new BookDatabaseHelper(this);
        
        SharedPreferences sharedPreferences = getSharedPreferences("UserData", Context.MODE_PRIVATE);
        currentUserEmail = sharedPreferences.getString("username", "");
        
        // 设置按钮点击事件
        btnAdd.setOnClickListener(v -> addBook());
        btnDelete.setOnClickListener(v -> deleteBook());
        btnUpdate.setOnClickListener(v -> updateBook());
        btnQuery.setOnClickListener(v -> queryBooks());
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        bookAdapter = new BookAdapter();
        recyclerView.setAdapter(bookAdapter);
        
        // 点击选中
        bookAdapter.setOnItemClickListener(book -> {
            selectedBook = book;
            etBookNo.setText(book.getBookNo());
            etBookName.setText(book.getBookName());
            Toast.makeText(this, "已选中：" + book.getBookName(), Toast.LENGTH_SHORT).show();
        });
        
        // 长按删除
        bookAdapter.setOnItemLongClickListener(book -> {
            new AlertDialog.Builder(this)
                    .setTitle("确认删除")
                    .setMessage("是否删除书籍：" + book.getBookName() + "?")
                    .setPositiveButton("删除", (dialog, which) -> {
                        int result = dbHelper.deleteBook(book.getId(), currentUserEmail);
                        if (result > 0) {
                            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                            loadAllBooks();
                            clearInputs();
                        } else {
                            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    // 添加书籍
    private void addBook() {
        String bookNo = etBookNo.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();
        
        if (TextUtils.isEmpty(bookNo)) {
            Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(bookName)) {
            Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Book book = new Book(bookNo, bookName, currentUserEmail);
        long id = dbHelper.addBook(book);
        
        if (id > 0) {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
            clearInputs();
            loadAllBooks();
        } else {
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 删除书籍
    private void deleteBook() {
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要删除的书籍", Toast.LENGTH_SHORT).show();
            return;
        }
        
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("是否删除书籍：" + selectedBook.getBookName() + "?")
                .setPositiveButton("删除", (dialog, which) -> {
                    int result = dbHelper.deleteBook(selectedBook.getId(), currentUserEmail);
                    if (result > 0) {
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        clearInputs();
                        loadAllBooks();
                    } else {
                        Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 修改书籍
    private void updateBook() {
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要修改的书籍", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String bookNo = etBookNo.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();
        
        if (TextUtils.isEmpty(bookNo)) {
            Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(bookName)) {
            Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
            return;
        }
        
        selectedBook.setBookNo(bookNo);
        selectedBook.setBookName(bookName);
        
        int result = dbHelper.updateBook(selectedBook);
        if (result > 0) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            clearInputs();
            loadAllBooks();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 查询书籍
    private void queryBooks() {
        String bookNo = etBookNo.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();
        
        List<Book> books;
        
        // 空查询显示全部
        if (TextUtils.isEmpty(bookNo) && TextUtils.isEmpty(bookName)) {
            loadAllBooks();
            return;
        }
        
        // 优先按书号查询
        if (!TextUtils.isEmpty(bookNo)) {
            books = dbHelper.searchByBookNo(bookNo, currentUserEmail);
        } else {
            books = dbHelper.searchByBookName(bookName, currentUserEmail);
        }
        
        bookAdapter.setBookList(books);
        Toast.makeText(this, "查询到 " + books.size() + " 条记录", Toast.LENGTH_SHORT).show();
    }

    // 加载所有书籍
    private void loadAllBooks() {
        List<Book> books = dbHelper.getAllBooks(currentUserEmail);
        bookAdapter.setBookList(books);
    }

    // 清空输入框
    private void clearInputs() {
        etBookNo.setText("");
        etBookName.setText("");
        selectedBook = null;
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
